package com.orangelife.mobile.lookRepair.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.common.sp.ShoppingSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.address.activity.MakeAddressListActivity;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.adapter.MyImageViewGridAdapter;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.biz.Photo;
import com.thirdsdk.qiniu.QiniuService;
import com.thirdsdk.qiniu.QiniuService.QiniuListener;
import com.common.jump.CommonJumper;
import com.orangelife.mobile.confirmOrder.activity.PayConfirmOrderActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.hourlyEmployee.activity.ServiceIntroductionActivity;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.photo.ImageActivity;
import com.orangelife.mobile.photo.MyGridView;
import com.orangelife.mobile.photo.PhotoActivity;
import com.orangelife.mobile.util.EmojiFilter;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房屋维修
 * <p/>
 * Create By yw.Modify by wgf on 160311
 *
 * @author yw, cfr, wgf
 * @version before v2.5.0
 */
public class LookForRepairActivity extends OrangeLifeBaseActivity {
    /** 标题中间的字 */
    private TextView tvTitle;
    /** 标题右边的字 */
    private TextView tvTitleRight;
    /** 维修问题 */
    private EditText etRepairContent;
    /** 照片的grideview */
    private MyGridView myGridView;
    private MyImageViewGridAdapter gvAdapter;
    /** 照片路径 */
    private List<String> paths;
    /** 地址 */
    private LinearLayout llAddress;
    /** 处理后的照片地址 */
    private String fileName = null;
    private TextView tvName;
    private TextView tvPhoneNumber;
    private TextView tvAddress;
    /** 上门费 */
    private TextView tvFee;
    private ImageView ivFee;
    /** 提交订单 */
    private Button btnSubmit;
    /** 限制的最大字数 */
    int num = 50;
    String str = "";
    private static final int WHAT_FEE = 3;
    private static final int WHAT_SERVICE = 5;
    private String feePrice;
    private String isAccessToken = "";
    private Map<String, Object> mapDetail = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lookfor_repair_add);
        initView();
        initImageGridView();
        setListener();
        requestFee();
        requestRepairInfo();
    }

    /** 获取上门费 */
    private void requestFee() {
        String url = Constant.URL_LOOKREPAIR_FEE;
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, null, handler, WHAT_FEE, HttpUtil.ACTION_URI);
    }

    private void handleFee(String response) {
        Map<String, Object> map = JSONHelper
                .jsonToMap(response);
        if (map != null) {
            if (map.get("errInfo").equals("OK")) {
                feePrice = String.valueOf(map.get("totalCost"));
                ivFee.setVisibility(View.VISIBLE);
                tvFee.setText("师傅上门费需" + feePrice + "元，可随时申请退款");
            } else {
                ToastHelper.getInstance().displayToastWithQuickClose("获取缴费金额失败");
            }
        }
    }

    /** 获取服务信息 */
    private void requestRepairInfo() {
        Map<String, Object> map = new HashMap<>();
        String districtID = ShoppingSp.getTradeDistrictID();
        if (TextUtils.isEmpty(districtID)) {
            districtID = CommSp2.getDistrictID();
        }
        map.put("districtID", districtID);
        String url = Constant.URL_LOOKREPAIR_GET_SERVICE;
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, map, handler, WHAT_SERVICE, HttpUtil.ACTION_URI);
    }

    private void handleRepairInfo(String response) {
        Map<String, Object> result = JSONHelper.jsonToMap(
                response);
        if (result == null) {
            return;
        }
        mapDetail = (Map<String, Object>) result.get("entity");
        if (mapDetail != null && mapDetail.size() != 0) {
            btnSubmit.setText("提交订单");
            btnSubmit.setEnabled(true);
        } else {
            btnSubmit.setText("所在区域尚未开通，敬请期待");
            btnSubmit.setEnabled(false);
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvFee = (TextView) findViewById(R.id.tvFee);
        ivFee = (ImageView) findViewById(R.id.ivFee);
        tvTitleRight = (TextView) findViewById(R.id.tv_title_right);
        etRepairContent = (EditText) findViewById(R.id.etRepairContent);
        myGridView = (MyGridView) findViewById(R.id.myGridview);
        llAddress = (LinearLayout) findViewById(R.id.llAddAddress);
        tvName = (TextView) findViewById(R.id.tv_username);
        tvPhoneNumber = (TextView) findViewById(R.id.tv_userphone);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        tvTitle.setText(R.string.lookfor_repair);
        tvTitleRight.setText(R.string.service_introduction);
        tvTitleRight.setVisibility(View.VISIBLE);
    }

    /** 给照片gridview设置apdater和监听事件 */
    private void initImageGridView() {
        /** 设置adapter */
        paths = new ArrayList<>();
        gvAdapter = new MyImageViewGridAdapter(
                LookForRepairActivity.this, paths, 5);
        myGridView.setAdapter(gvAdapter);
        /** 监听事件 */
        myGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                                    int position, long arg3) {
                jumpToPhotoOrImage(position);
            }
        });
    }

    private void setListener() {
        btnSubmit.setOnClickListener(listener);
        llAddress.setOnClickListener(listener);
        tvTitleRight.setOnClickListener(listener);
        etRepairContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;
            /** 匹配非表情符号的正则表达式 */
            /*private final String reg = "^([a-z]|[A-Z]|[0-9]|[\u2E80-\u9FFF]){3,}|@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$";

			private Pattern pattern = Pattern.compile(reg);*/
            /** 输入表情前的光标位置 */
            private int cursorPos;
            /** 输入表情前EditText中的文本 */
            private String tmp;
            /** 是否重置了EditText的内容 */
            private boolean resetText;

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if ("".equals(str)) {
                    if (!resetText) {
                        /** 表情符号的字符长度最小为2 */
                        if (count >= 2) {
                            /** 提取输入的长度大于2的文本 */
                            if (s.length() <= num) {
                                CharSequence input = s.subSequence(start,
                                        start + count);
                                /** 正则匹配是否是表情符号 *//*
                                Matcher matcher = pattern.matcher(input
										.toString());*/
                                if (!EmojiFilter.containsEmoji(input.toString())) {
                                    resetText = true;
                                    /** 是表情符号就将文本还原为输入表情符号之前的内容 */
                                    etRepairContent.setText(tmp);
                                    etRepairContent.invalidate();
                                    ToastHelper.getInstance()._toast("不支持表情输入");
                                    etRepairContent.setSelection(tmp.length());
                                }
                            } else {
                                str = "over";
                            }
                        }
                    } else {
                        resetText = false;
                    }
                }

                temp = s;
                Log.e("hhhhhhhh", s + "");
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                if (!resetText) {
                    cursorPos = etRepairContent.getSelectionEnd();
                    /**
                     * 这里用s.toString()而不直接用s是因为如果用s，那么，tmp和s在内存中指向的是同一个地址，s改变了，
                     * tmp也就改变了，那么表情过滤就失败了
                     */
                    tmp = s.toString();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                selectionStart = etRepairContent.getSelectionStart();
                selectionEnd = etRepairContent.getSelectionEnd();
                if (temp.length() > num) {
                    s.delete(selectionStart - 1, selectionEnd);
                    ToastHelper.getInstance()._toast("维修问题要在50字以内");
                    etRepairContent.setText(s);
                }
            }
        });
    }

    /**
     * 监听器
     */
    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnSubmit:
                    if (!checkCommitOrder()) {
                        return;
                    }
                    checkImageBeforeJumpToCommitOrder();
                    break;
                case R.id.tv_title_right:
                    jumpToServiceIntroduction();
                    break;
                default:
                    break;
            }
        }
    };

    /** 跳转到说明界面 */
    private void jumpToServiceIntroduction() {
        if (mapDetail == null || mapDetail.size() == 0) {
            ToastHelper.getInstance()._toast("暂无该地区服务介绍");
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("url", mapDetail.get("url").toString());
        intent.putExtra("activ", 2);
        intent.setClass(LookForRepairActivity.this, ServiceIntroductionActivity.class);
        startActivity(intent);
    }

    /** 在跳转前检查图片 */
    private void checkImageBeforeJumpToCommitOrder() {
        if (paths.size() == 0) {
            jumpToCommitOrder();
        } else {
            QiniuService qiniu = new QiniuService();
            showDialog();
            qiniu.imgUpload(paths, new QiniuListener() {

                @Override
                public void request(String fileNames) {
                   closeDialog();
                    if (fileNames.equals("500")) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.photo_save_faild));
                    } else {
                        fileName = fileNames;
                        jumpToCommitOrder();
                    }
                }
            });
        }
    }

    /** 跳转到提交订单界面 */
    private void jumpToCommitOrder() {

        Map<String, Object> mapDetail = new HashMap<>();
        mapDetail.put("orderInfo", etRepairContent.getText().toString());
        mapDetail.put("shipName", tvName.getText().toString());
        mapDetail.put("shipAddr", tvAddress.getText().toString());
        mapDetail.put("shipPhone", tvPhoneNumber.getText().toString());
        if (fileName == null) {
            mapDetail.put("pics", "null");
        } else {
            mapDetail.put("pics", fileName);
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", (Serializable) mapDetail);
        Intent intent = new Intent();
        intent.putExtra(PaymentModule.PAID_METHOD, PaymentModule.mode[3]);
        intent.putExtra("feeType", 2);
        intent.putExtra("Payment", feePrice);
        intent.putExtras(bundle);
        intent.setClass(LookForRepairActivity.this, PayConfirmOrderActivity.class);
        startActivity(intent);
        ExitApplication.getInstance().addPaidActivity(LookForRepairActivity.this);
    }

    /** 检验提交订单信息 */
    private boolean checkCommitOrder() {
        String content = etRepairContent.getText().toString();
        if (StringUtil.isBlank(content)) {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getTxt(
                            R.string.please_fill_content));
            return false;
        }
        if ("".equals(tvName.getText().toString())) {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getResources().getString(
                            R.string.please_fill_address));
            return false;
        }
        return true;
    }

    /** 跳转到拍照或相册界面 */
    private void jumpToPhotoOrImage(int position) {
        if (position == paths.size()) {
            Intent intent = new Intent(
                    LookForRepairActivity.this,
                    PhotoActivity.class);
            startActivityForResult(intent, 5);
        } else {

            Intent intent = new Intent(
                    LookForRepairActivity.this,
                    ImageActivity.class);
            intent.putExtra("position", position);
            intent.putExtra("path", paths.get(position));
            startActivityForResult(intent, 88);
        }
    }

    private void handleJumpBackPhotoOrImage(int requestCode, int resultCode, Intent data) {
        if (requestCode == 5 && resultCode == 99) {
            if (data != null) {
                String photoPath = data.getStringExtra("photoPath");
                paths.add(photoPath);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            } else {
                if (photo.photoUri != null) {
                    String photoPath = photo.photoUri.getPath();
                    paths.add(photoPath);
                    gvAdapter.resetImage(paths);
                    gvAdapter.notifyDataSetChanged();
                }

            }
        } else if (requestCode == 6 && resultCode == 99) {
            if (data != null) {
                String photoPath = Photo.getPath(data);
                paths.add(photoPath);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            }

        } else if (requestCode == 88 && resultCode == 88) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                int position = bundle.getInt("position");
                paths.remove(position);
                gvAdapter.resetImage(paths);
                gvAdapter.notifyDataSetChanged();
            }
        } else if (requestCode == Activity.RESULT_FIRST_USER) {
            requestRepairInfo();
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 接收处理线程返回的消息
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            String response = String.valueOf(msg.obj);
            closeDialog();
            switch (msg.what) {
                case Constant.WHAT_ERROR_HTTP:
                    if ("10025".equals(response)) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.send_sms_success));
                    } else {
                        ToastHelper.getInstance()._toast(response);
                    }
                    break;
                case WHAT_FEE:
                    handleFee(response);
                    break;
                case WHAT_SERVICE:
                    handleRepairInfo(response);
                    break;
                case 13:
                    HashMap<String, Object> mapAccessToken = new HashMap<String, Object>();
                    mapAccessToken = (HashMap<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    if ("true".equals(mapAccessToken.get("online"))) {
                        isAccessToken = "true";
                    } else {
                        isAccessToken = "false";
                    }
                    if ("true".equals(isAccessToken)) {
                        IntentHelper.getInstances().getIntent(LookForRepairActivity.this, MakeAddressListActivity.class);
                    } else if ("false".equals(isAccessToken)) {
                        ToastHelper.getInstance()._toast("请先登录");
                        CommonJumper.jumpToLoginWhenExitWithClear(LookForRepairActivity.this);
                    }
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                case 1:
                    String errInfo = JSONHelper.jsonToMap(response)
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        ToastHelper.getInstance()._toast(getResources().getString(R.string.submit_success));
                        CommonJumper.jumpToMain(LookForRepairActivity.this);
                    } else {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
            }
        }

        ;
    };

    Photo photo = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        handleJumpBackPhotoOrImage(requestCode, resultCode, data);
    }

    private String getTxt(int id) {
        return getResources().getString(
                id);
    }
}
